package mx.webuilder.tools;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javafx.scene.control.Button;
import javafx.scene.control.Control;
import javafx.scene.layout.GridPane;

public abstract class MyTable<T> {
	private Map<String, String> columns = new LinkedHashMap<>();
	private Map<String, Class> clazzs =new LinkedHashMap<>();
	private List<Map<String, Control>> data = new ArrayList<>();
	private GridPane pane = null;
	
	public abstract T record2Object(Map<String, Control> record) throws Exception;
	public abstract void object2record(T object, Map<String, Control> record) throws Exception;
	
	public GridPane initPane() throws Exception {
		pane = new GridPane();
		refresh();
		return pane;
	}
	
	public void refresh() {
		pane.getChildren().clear();
		
		int col = 0;
		for (String key : columns.keySet()) {
			String title = columns.get(key);
			pane.add(new Button(title), col, 0);
			col ++;
		}
		
		col = 0;
		for (int i=0; i<data.size(); i++) {
			Map<String, Control> record = data.get(i);
			for (String key : record.keySet()) {
				Control x = record.get(key);
				pane.add(x, col, i+1);
				col++;
			}
		}

	}
	
	public void delete(int index) throws Exception {
		data.remove(index);
		this.refresh();
	}
	
	public Map<String, Control> newBlankRecord() throws Exception {
		Map<String, Control> record = new LinkedHashMap<>();
		for (String key : clazzs.keySet()) {
			Class clazz = this.clazzs.get(key);
			record.put(key, (Control) clazz.newInstance());
		}
		
		int row = data.size() + 1;
		int col = 0;
		for (String key : record.keySet()) {
			Control x = record.get(key);
			pane.add(x, col, row);
			col++;
		}
		
		return record;
	}
	
	public void writeData(List<T> objects) throws Exception {
		data.clear();
		
		for (int i=0; i<objects.size(); i++) {
			T object = objects.get(i);
			Map<String, Control> record = newBlankRecord();
			object2record(object, record);
			data.add(record);
		}
		
		refresh();
	}
	
	public List<T> readData() throws Exception {
		List<T> objects = new ArrayList<>();
		for (int i=0; i<data.size(); i++) {
			Map<String, Control> record = data.get(i);
			T object = this.record2Object(record);
			objects.add(object);
		}		
		return objects;
	}
}
